﻿using System;
using System.Windows;
using Foundation.MarkupExtensions;
using ICSharpCode.AvalonEdit;
using Poet.ViewModels;
using Application = System.Windows.Application;
using ToolBar = System.Windows.Controls.ToolBar;

namespace Poet.Views
{
    /// <summary>
    /// Interaction logic for DocumentView.xaml
    /// </summary>
    public partial class DocumentView : IDisposable
    {
        internal DocumentViewModel ViewModel
        {
            get { return DataContext as DocumentViewModel; }
        }

        internal static readonly DependencyProperty TextEditorProperty =
            DependencyProperty.Register("TextEditor", typeof(TextEditor), typeof(DocumentView),
                                        new PropertyMetadata(default(TextEditor)));

        internal TextEditor TextEditor
        {
            get { return (TextEditor)GetValue(TextEditorProperty) ?? SplitableTextEditor.TextEditorView; }
            set
            {
                SetValue(TextEditorProperty, value);
                if (ViewModel != null)
                    ViewModel.ActiveTextEditorView = value;
                DefaultElement = value;
            }
        }

        public DocumentView()
        {
            InitializeComponent();
            TextEditor = SplitableTextEditor.TextEditorView;
            Loaded += delegate { if (TextEditor != null) TextEditor.Focus(); };
            SplitableTextEditor.OnTextEditorChanged += te => TextEditor = te;

            var toolBars = (XamlCollection)Resources["DocumentToolBarCollection"];
            foreach (ToolBar toolBar in toolBars)
                ToolBarTray.ToolBars.Add(toolBar);

            DataContextChanged += (sender, args) =>
                {
                    if (ViewModel == null)
                    {
                        CommandBindings.Clear();
                        TextEditor = null;
                        SplitableTextEditor.TextCompositionEventHandler = (o, eventArgs) => { };
                        SplitableTextEditor.MouseWheelEventHandler = (o, eventArgs) => { };
                        return;
                    }

                    SplitableTextEditor.TextCompositionEventHandler = ViewModel.PreviewTextEntered;
                    SplitableTextEditor.MouseWheelEventHandler = ViewModel.OnPreviewMouseWheel;

                    var viewModel = (DocumentViewModel)DataContext;
                    CommandBindings.AddRange(viewModel.CommandBindings);
                    viewModel.OnClosing += (o, eventArgs) => Close();
                };

            Closed += (sender, args) => Application.Current.MainWindow.Focus();
        }

        public void Dispose()
        {
            if (ViewModel != null)
                ViewModel.Dispose();
            DataContext = null;
        }
    }
}
